﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

using ImageRecognition2.Forms;
using LowLevelGraphics;
using LowLevelGraphics.ColorSpaces;

namespace ImageRecognition2.Action
{
    /// <summary>
    /// 
    /// </summary>
    public class ActionExtractChannels : AbstractCommand
    {
        protected Type m_AbstractColorSpace = typeof(LowLevelGraphics.ColorSpaces.RGB);

        /// <summary>
        /// 
        /// </summary>
        public ActionExtractChannels()
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_actionExtractChannels"></param>
        internal ActionExtractChannels(ActionExtractChannels _actionExtractChannels)
        {
        }

        public Type ColorSpace
        {
            get { return m_AbstractColorSpace; }
            set { m_AbstractColorSpace = value; }
        }

        public override void Run(object sender, EventArgs e)
        {
            UnsafeBitmap bitmap = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage.Clone();
            if (bitmap == null) return; //This shouldn't normally happen!
            int nWidth = bitmap.Width;
            int nHeight = bitmap.Height;

            AbstractColorSpace abstractColorSpace = (AbstractColorSpace)Activator.CreateInstance(m_AbstractColorSpace, Definitions.Black);
            int nCount = abstractColorSpace.GetValues().Length;

            FormChild[] aFormChild = new FormChild[nCount];
            UnsafeBitmap[] aBitmap = new UnsafeBitmap[nCount];

            int i = 0;
            for (i = 0; i < nCount; i++)
            {
                aFormChild[i] = GuiHelper.CreateNewChild();
                aBitmap[i] = (UnsafeBitmap)bitmap.Clone();
                aBitmap[i].Dispose();
                aFormChild[i].pictureBox1.BackgroundImage = bitmap.InternalBitmap;
                aBitmap[i].LockImage();
            }

            for (int y = 0; y < nHeight; y++)
            {
                for (int x = 0; x < nWidth; x++)
                {
                    abstractColorSpace.Color = bitmap.GetPixel(x, y);
                    for (i = 0; i < nCount; i++)
                    {
                        aBitmap[i].SetGrayPixel(x, y, int.Parse(abstractColorSpace.GetValues()[i].ToString()));
                    }
                }
            }
            for (i = 0; i < nCount; i++)
            {
                aBitmap[i].Dispose();
            }
            bitmap.Dispose();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new ActionExtractChannels(this);
        }
    }
}
